package com.czl.module_service.viewmodel.inventory

import com.blankj.utilcode.util.GsonUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.tengyun.InventoryAssetBean
import com.czl.base.data.bean.tengyun.ListBean
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper

/**
 * @author by xubin
 * PS: Not easy to write code, please indicate.
 */
class InventoryHomeViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {
    var pageNo = 1
    val uc = UiChangeEvent()

    inner class UiChangeEvent {
        val loadCompleteEvent: SingleLiveEvent<ListBean<InventoryAssetBean>?> = SingleLiveEvent()
    }

    val onLoadMoreListener: BindingCommand<Void> = BindingCommand(BindingAction {
        wechatGetMyTaskList()
    })
    val onRefreshListener: BindingCommand<Void> = BindingCommand(BindingAction {
        pageNo = 1
        wechatGetMyTaskList()
    })

    private fun wechatGetMyTaskList() {
        model.mTengYunHttpDataSource
            .wechatGetMyTaskList(
                GsonUtils.toJson(
                    mapOf(
                        "pageNo" to pageNo,
                        "pageSize" to 10,
                        "userId" to model.getLocalUserInfo()?.userId,
                        "companyId" to model.getLocalUserInfo()?.companyId
                    )
                )
            )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<ListBean<InventoryAssetBean>>>() {
                override fun onResult(t: BaseBean<ListBean<InventoryAssetBean>>) {
                    if (t.state == 0) {
                        pageNo++
                        uc.loadCompleteEvent.postValue(t.data)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }
}